<template>
  <el-dialog
    v-model="dialogVisible"
    title="截图查看"
    width="70%"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="screenshot-viewer">
      <div v-if="imageUrl" class="image-container">
        <img
          :src="imageUrl"
          :alt="'截图'"
          class="screenshot-image"
          @load="handleImageLoad"
          @error="handleImageError"
        />
      </div>
      <div v-else class="no-image">
        <el-icon size="48" color="#ccc"><Picture /></el-icon>
        <p>暂无截图</p>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button v-if="imageUrl" type="primary" @click="downloadImage">
          <el-icon><Download /></el-icon>
          下载图片
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture, Download } from '@element-plus/icons-vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  imageUrl: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:visible'])

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 方法
const handleClose = () => {
  dialogVisible.value = false
}

const handleImageLoad = () => {
  // 图片加载成功
}

const handleImageError = () => {
  ElMessage.error('图片加载失败')
}

const downloadImage = async () => {
  if (!props.imageUrl) return
  
  try {
    const response = await fetch(props.imageUrl)
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    
    const link = document.createElement('a')
    link.href = url
    link.download = `screenshot_${Date.now()}.png`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    window.URL.revokeObjectURL(url)
    ElMessage.success('图片下载成功')
  } catch (error) {
    console.error('下载图片失败:', error)
    ElMessage.error('图片下载失败')
  }
}
</script>

<style lang="scss" scoped>
.screenshot-viewer {
  .image-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
    
    .screenshot-image {
      max-width: 100%;
      max-height: 60vh;
      object-fit: contain;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }
  
  .no-image {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    min-height: 300px;
    color: #ccc;
    
    p {
      margin: 12px 0 0 0;
      font-size: 14px;
    }
  }
}

.dialog-footer {
  text-align: right;
  
  .el-button {
    margin-left: 8px;
  }
}

:deep(.el-dialog) {
  .el-dialog__body {
    padding: 20px;
  }
}
</style>
